package practice_2025_8_15;

import java.util.*;


public class Solution {
    /**
     * 矩阵最长递增路径
     */
     int[] dx = {0, 0, 1, -1};
     int[] dy = {1, -1, 0, 0};
     int m;
     int n;
     int[][] steps;
    public int solve (int[][] matrix) {
        // write code here
        m = matrix.length;
        n = matrix[0].length;
        int max = 0;
        steps = new int[m][n];
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                max = Math.max(max, dfs(matrix, i, j));
            }
        }
        return max;
    }

    public int dfs(int[][] matrix, int x, int y) {
        // 递归出口
        int count = 1;
        for(int i = 0; i < dx.length; i++) {
            int nextX = x + dx[i];
            int nextY = y + dy[i];
            // 继续递归
            if (nextX >= 0 && nextX < m 
            && nextY >= 0 && nextY < n
            && matrix[nextX][nextY] > matrix[x][y]){
                if (steps[nextX][nextY] > 0) {
                    count = Math.max(count, steps[nextX][nextY] + 1);
                } else {
                    count = Math.max(count, dfs(matrix, nextX, nextY) + 1);
                }
            }
        }
        // 记录
        steps[x][y] = count;
        return count;
    }


    int[][] memo;

    /**
     * 猜数字大小II
     * @param n
     * @return
     */
    public int getMoneyAmount(int n) {
        memo = new int[n + 1][n + 1];
        return dfs(1, n);
    }
    public int dfs(int left, int right) {
        // 只有一个数字, 只需花费0
        if (left >= right) {
            return 0;
        }
        if (memo[left][right] != 0) {
            return memo[left][right];
        }
        int res = Integer.MAX_VALUE;
        for(int i = left; i <= right; i++) {
            int leftCost = dfs(left, i - 1);
            int rightCost = dfs(i + 1, right);
            int cost = Math.max(leftCost, rightCost) + i;
            res = Math.min(res, cost);
        }
        memo[left][right] = res;
        return res;
    }
}